package prog1.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: Roi
 * Date: 05/12/13
 */
public class Utils {

    /**
     * @param args program arguments
     * @return key store password
     * @throws Exception
     */
    public static String getKeyStorePassword(String[] args) throws Exception {
        if(args.length == 0)
            throw new Exception("missing key store password argument");

        return args[0];
    }

    /**
     * Reads given file and returns its content as a string
     * @param filename source filename
     * @return file's content
     * @throws IOException
     */
    public static String fileToString(String filename) throws IOException {
        File file = new File(filename);

        BufferedReader reader = new BufferedReader(new FileReader(file));
        StringBuilder result = new StringBuilder();
        String line;
        String separator = System.getProperty("line.separator");

        while ((line = reader.readLine()) != null) {
            result.append(line);
            result.append(separator);
        }

        return result.toString();
    }

    /**
     * Parses byte array
     * @param size array size
     * @param str string representation of byte array
     * @return parsed byte array
     */
    public static byte[] parseByteArray(int size, String str) {
        byte[] result = new byte[size];
        String[] iv = str.replace("[", "").replace("]", "").split(", ");

        for (int i = 0; i < result.length; i++) {
            result[i] = Byte.parseByte(iv[i]);
        }

        return result;
    }

    /**
     * Prints message
     * @param message message to print
     */
    public static void log(String message) {
        System.out.println(message);
    }
}
